package cn.tl.hrm.exception;

import cn.tl.hrm.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //RestController通知
@Slf4j //lombok 日志注解
public class GlobalExceptionHandler {

    //private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //处理自定义异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        //e.printStackTrace();
        //logger.error("出错啦！"+e.getMessage());
        ErrorCode errorCode = e.getErrorCode();
        log.error("出错啦！"+errorCode.getCode()+":"+errorCode.getMessage());
        return  AjaxResult.me()
                .setSuccess(false)
                .setCode(errorCode.getCode())
                .setMessage(errorCode.getMessage());
    }

    //处理jsr303错误
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){

        //获取多个字段参数校验
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        //拼接错误提示信息
        StringBuffer sb = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getDefaultMessage()+",");
        }
        String msg = sb.toString();
        msg= msg.substring(0,msg.length()-1);

        //e.printStackTrace();
        log.error("出错啦！"+msg); //debug info warning error!
        return  AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_400_PARAM_ERROR.getCode())
                .setMessage(msg);
    }
    //处理自定义异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        //logger.error("出错啦！"+e.getMessage());
        log.error("出错啦！"+e.getMessage()); //debug info warning error!
        return  AjaxResult.me().setSuccess(false)
                .setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode())
                .       setMessage(ErrorCode.CODE_500_SYSTEM_ERROR.getMessage());
    }
}